package com.cbts.util;

import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.BodyPart;

import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
/**
 * @author 邱鸿辉
 *
 */
public class MailSender {

	private MimeMessage mimeMsg; // mime邮件对象
	private Session session; // 邮件回话对象
	private Properties props = System.getProperties(); // 系统属性
	private boolean needAuth = false; // smtp是否需要认证

	// smtp验证用户名和密码
	private String username;
	private String password;
	private Multipart mp; // 邮件内容
	private String localHost;//服务器ip
	private String localPort;//运行项目的服务器端口号
	private String progectName;//项目名
	public String getProgectName() {
		return progectName;
	}
	public void setProgectName(String progectName) {
		this.progectName = progectName;
	}
	public MimeMessage getMimeMsg() {
		return mimeMsg;
	}
	public void setMimeMsg(MimeMessage mimeMsg) {
		this.mimeMsg = mimeMsg;
	}
	public String getLocalPort() {
		return localPort;
	}
	public void setLocalPort(String localPort) {
		this.localPort = localPort;
	}
	public String getLocalHost() {
		return localHost;
	}
	public void setLocalHost(String localHost) {
		this.localHost = localHost;
	}
	public void setUsername(String username) {/*System.out.println("2");*/
		this.username = username;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	/** 
     * Constructor 
     * @param smtp 邮件发送服务器 
     * @param port 端口号
     */ 
	public MailSender(){
		createMimeMessage();
	}
	/*public MailSender(String smtp, String port) {
		setSmtpHost(smtp); 
		setSmtpPort(port);
        createMimeMessage();   
	}*/

	/**
	 * 设置发送服务器
	 * @param hostName
	 */
	public void setSmtpHost(String smtpHost) {
		
		props.put("mail.smtp.host", smtpHost);
	}
	
	/**
	 * 设置端口号
	 * @param port
	 */
	public void setSmtpPort(String smtpPort) {
		
		props.put("mail.smtp.port", smtpPort);
	}

	/**
	 * 创建mime对象
	 * @return 成功创建mime对象则返回true，否则返回false
	 */
	public boolean createMimeMessage(){
		try{
			session = Session.getDefaultInstance(props,null); //获得邮件会话对象  
			mimeMsg = new MimeMessage(session); //创建MIME邮件对象   
	        mp = new MimeMultipart();
	        return true;
		}catch(Exception e){
			return false;
		}
	}
	
	/**
	 * 设置smtp是否需要验证
	 * @param need 
	 */
	public void setNeedAuth(boolean needAuth){
		 
        if(needAuth){   
            props.put("mail.smtp.auth","true");   
        }else{   
            props.put("mail.smtp.auth","false");   
        }   
	}
	
	/**
	 * 设置smtp验证用户名和密码
	 * @param name
	 * @param pass
	 */
	/*public void setSmtpInfo(String name,String pass){
		username=name;
		password=pass;
	}*/
	
	/** 
     * 设置邮件主题 
     * @param mailSubject String
     * @return  成功设置邮件主题则返回true，否则返回false
     */  
    public boolean setSubject(String mailSubject) {    
        try{   
            mimeMsg.setSubject(mailSubject);   
            return true;   
        }   
        catch(Exception e) {
        	e.printStackTrace();
            return false;   
        }   
    }  
    
    /**  
     * 设置邮件正文 
     * @param mailBody String  
     * @return 设置邮件正文成功返回true，否则返回false
     */   
    public boolean setBody(String mailBody) {   
        try{   
            BodyPart bp = new MimeBodyPart();   
            bp.setContent(""+mailBody,"text/html;charset=UTF-8");   
            mp.addBodyPart(bp);   
          
            return true;   
        } catch(Exception e){   
        	return false;   
        }   
    }
    
    /**  
     * 添加附件 
     * @param filename String  
     */   
    public boolean addFileAffix(String filename) {   
      
        System.out.println("增加邮件附件："+filename);   
        try{   
            BodyPart bp = new MimeBodyPart();   
            FileDataSource fileds = new FileDataSource(filename);   
            bp.setDataHandler(new DataHandler(fileds));   
            bp.setFileName(fileds.getName());   
              
            mp.addBodyPart(bp);   
              
            return true;   
        } catch(Exception e){     
            return false;   
        }   
    }  
    
    /**  
     * 设置发信人 
     * @param from 发信人邮箱 
     */   
    public boolean setFrom(String from){   
       // System.out.println("设置发信人！");   
        try{   
            mimeMsg.setFrom(new InternetAddress(from)); //设置发信人   
            return true;   
        } catch(Exception e) {   
            return false;   
        }   
    }   
    
    /**  
     * 设置收信人 
     * @param to 收信人邮箱  
     */   
    public boolean setTo(String to){   
        if(to == null)return false;   
        try{   
            mimeMsg.setRecipients(Message.RecipientType.TO,InternetAddress.parse(to));   
            return true;   
        } catch(Exception e) {   
            return false;   
        }     
    }   
      
    /**  
     * 设置抄送人 
     * @param copyto String   
     */   
    public boolean setCopyTo(String copyto){   
        if(copyto == null)return false;   
        try{   
	        mimeMsg.setRecipients(Message.RecipientType.CC,(Address[])InternetAddress.parse(copyto));   
	        return true;   
        }   
        catch(Exception e){ 
        	return false;
        }   
    }   
    
    /**  
     * 发送邮件 
     */   
    public boolean sendOut(){   
        try{   
            mimeMsg.setContent(mp);	//设置内容
            mimeMsg.saveChanges();   
            System.out.println("正在发送邮件....");   
              
            Session mailSession = Session.getInstance(props,null);   
            Transport transport = mailSession.getTransport("smtp");   //发送
            transport.connect((String)props.get("mail.smtp.host"),username,password);   
            transport.sendMessage(mimeMsg,mimeMsg.getRecipients(Message.RecipientType.TO));   
            //transport.sendMessage(mimeMsg,mimeMsg.getRecipients(Message.RecipientType.CC));   
            //transport.send(mimeMsg);   
              
            System.out.println("发送邮件成功！");   
            transport.close();   
              
            return true;   
        } catch(Exception e) {   
            System.err.println("邮件发送失败！"+e);   
            return false;   
        }   
    }
    
    /** 
     * 调用sendOut方法完成邮件发送 
     * @param to 收信人
     * @param subject 主题
     * @param content 内容
     * @return boolean 成功发送返回true,否则返回false
     */  
    public  boolean send(String to,String subject,String content) {  
       /* MailSender mail = new MailSender(smtp,port);  
        mail.setNeedAuth(true); //需要验证  
*/          
        if(!setSubject(subject)) return false;  
        if(!setBody(content)) return false;  
        if(!setTo(to)) return false;  
      /*  if(!mail.setFrom(from)) return false;  
        mail.setSmtpInfo(username,password); */ 
          
        if(!sendOut()) return false;  
        return true;  
    } 
}
